//
//  NDOnBoardingView.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/24.
//

import SwiftUI

struct NDOnBoardingView: View {
    
    @EnvironmentObject private var appState: NDAppState
    @State private var hiddenRetryButton = true
    
    var body: some View {
    
        ZStack {
            backgroundView
            VStack {
                Spacer()
                retryButton
                    .hidden(hiddenRetryButton)
                Spacer()
                    .frame(height: bottomSafeArea + 60)
            }
        }
        .ignoresSafeArea()
        .onAppear {
            hiddenRetryButton = true
            loadEnvironment()
        }
    }
    
    var retryButton: some View {
        Button(action: retry) {
            Text("Retry")
                .font(.system(size: 14, weight: .bold))
                .foregroundColor(Color(hex: "#FFFFFF"))
                .frame(width: 106, height: 36)
                .background(Color(hex: "#FD632B"))
                .clipShape(Capsule())
        }
        .buttonStyle(FullSizeButtonStyle())
    }
    
    func retry() {
        loadEnvironment() 
    }
    
    var backgroundView: some View {
        Image("lounch_bg")
            .resizable()
            .scaledToFill()
            .ignoresSafeArea()
    }
    
    func loadEnvironment() {
        NDProgressHUD.show()
        NDRequestManager.requestEnvironment { appEnvironment, message, error in
            if error == nil {
                hiddenRetryButton = true
                if let countryId = appEnvironment?.governmentic {
                    NDUserDefaults.shared.saveText(countryId, for: NDRegionCodeKey)
                }
                
                if NDLoginInfo.shared.isLogined {
                    appState.rootView = .main
                } else {
                    appState.rootView = .login
                }
                NDProgressHUD.dismiss()
            } else {
                hiddenRetryButton = false
                NDProgressHUD.showInfo(message)
            }
        }
    }
}

